import pandas as pd
import yaml

from yaml import SafeLoader

from datareport.api import ImageUtil
from datareport.api.DataSource import DataSource
from datareport.api.annotation.Font import Font
from datareport.impl.paragraph.base.BaseParagraph import BaseParagraph
from datareport.api.annotation.Style import style


@style()
class KaiZhanQingKuang_one_erji_35(BaseParagraph):
    """
    从二级党组织层面看完成度情况
    """
    decrease=40

    def __init__(self):
        super().__init__()
        self.text = '''从二级党组织层面看完成度情况看：最低达{}%，最高达{}%。'''
        self.fonts=[
             ]
        self.sort = 25
        self.section = 7

    def plot(self, df, plt):
        pass

    def getData(self, result):
        pass

    def start(self, conn, year, plt):
        plan=pd.read_sql('''select p.*,r.num num1 from (
        select partyOrgName,month,count(*) num from t_meetingplan  where isPlan=1 and completeStatus='通过'
        group by partyOrgName,month) p left join (select i.partyOrgName,month(i.createTime) month,count(1) num from t_meetingrecord r 
                                            left join t_meetinginfo i on r.meetingInfoId=i.id 
                                           
        group by i.partyOrgName,month(i.createTime)) r on p.partyOrgName=r.partyOrgName and p.month=r.month
        ''',con=conn)
        plan=plan.fillna(0)
        org_percent_df=plan.groupby('partyOrgName').sum()
        org_month_percent_df=plan.groupby(['partyOrgName','month']).sum().reset_index(drop=False)
        org_month_percent_df['month'] = org_month_percent_df['month'].astype(str) + '月'
        org_month_percent_df.rename(columns={'partyOrgName':"二级党组织",'month':'月份'},inplace=True)
        org_percent_df['percent']=round(100*org_percent_df['num1']/org_percent_df['num'],1)
        org_month_percent_df['完成率']=round(100*org_month_percent_df['num1']/org_month_percent_df['num'],1)
        ##最高
        max_percent=org_percent_df['percent'].max()
        ##最低
        min_percent=org_percent_df['percent'].min()
        ##月度
        plan['percent']=round(100*plan['num1']/plan['num'],1)
        max_diff=0
        for o in plan['partyOrgName'].values.tolist():
            temp=plan[plan['partyOrgName']==o].sort_values('percent')
            diff=temp.iloc[-1]['percent']-temp.iloc[0]['percent']
            if diff>max_diff:
                max_diff=diff

        self.text=self.text.format(min_percent,max_percent)
        self.fonts.append(Font(text=self.text))
        temp=pd.read_sql('''select partyOrgName '二级党组织',round(100*avg(percent),1) '申报率(%)' from (
        select partyOrgName,
                    case when activityId in (select activityId from t_meetingplan) then 1 else 0 end percent 
                    from t_meetinginfo)new group by partyOrgName''',con=conn)
        self.tables.append(org_month_percent_df[['二级党组织','月份','完成率']])
        self.tables.append(temp)
        self.image=ImageUtil.line(org_percent_df.index.tolist(),
                       org_percent_df['percent'].values.tolist(),
                       '二级党组织月度完成度情况')



if __name__ == '__main__':
    with open('D:\work\sanhuiyike\datareport\config.yaml', encoding='utf-8') as f:
        data = yaml.load(f, Loader=SafeLoader)
    con=DataSource(data['datasource']).conn
    KaiZhanQingKuang_one_erji_35().start(con,2023,'')
